<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>工单审核</title>
    <style>
        html,
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        body {
            background: linear-gradient(135deg, #0f1629 0%, #1a1f35 100%);
            height: 100%;
            width: 100%;
        }

        .content {
            width: 100%;
            height: 100%;
            overflow: auto;
            color: #cbd5e1;
            background: rgba(26, 30, 48, 0.95);
            backdrop-filter: blur(10px);
            padding: 4%;
            box-sizing: border-box;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
            -webkit-overflow-scrolling: touch;
        }

        #content-detail {
            width: 100%;
            height: 100%;
            overflow: auto;
        }

        .row {
            background: rgba(30, 41, 59, 0.5);
            margin: 8px 0;
            border-radius: 12px;
            padding: 12px 16px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
            border: 1px solid rgba(148, 163, 184, 0.1);
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .row:hover {
            background: rgba(59, 130, 246, 0.15);
            border-color: rgba(59, 130, 246, 0.3);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.2);
        }

        .row:active {
            transform: translateY(0);
            transition: all 0.1s ease;
        }

        .row::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.5s ease;
        }

        .row:hover::before {
            left: 100%;
        }

        .workflow-name {
            flex: 1;
            min-width: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-weight: 400;
            color: #f1f5f9;
        }

        .workflow-status {
            flex: 0 0 30%;
            text-align: center;
            padding: 0 8px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .workflow-actions {
            flex: 0 0 30%;
            text-align: center;
            padding-left: 8px;
            display: flex;
            gap: 4px;
            justify-content: flex-end;
            align-items: center;
        }

        .workflow-time {
            color: #94a3b8;
            font-size: 0.75rem;
            font-weight: 500;
            white-space: nowrap;
        }

        .btn {
            border: none;
            color: #fff;
            border-radius: 6px;
            padding: 4px 8px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            white-space: nowrap;
            flex-shrink: 0;
            font-size: 0.75rem;
            font-weight: 600;
            min-width: 50px;
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: width 0.3s ease, height 0.3s ease;
        }

        .btn:active::before {
            width: 200px;
            height: 200px;
        }

        .btn:active {
            transform: scale(0.95);
        }

        .btn-primary {
            background: linear-gradient(135deg, #3b82f6, #60a5fa);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }

        .btn-primary:hover {
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.5);
        }

        .btn-success {
            background: linear-gradient(135deg, #059669, #10b981);
            box-shadow: 0 4px 12px rgba(5, 150, 105, 0.3);
        }

        .btn-success:hover {
            box-shadow: 0 6px 20px rgba(5, 150, 105, 0.5);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #fbbf24);
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
        }

        .btn-warning:hover {
            box-shadow: 0 6px 20px rgba(245, 158, 11, 0.5);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc2626, #ef4444);
            box-shadow: 0 4px 12px rgba(220, 38, 38, 0.3);
        }

        .btn-danger:hover {
            box-shadow: 0 6px 20px rgba(220, 38, 38, 0.5);
        }

        .status-finish {
            color: #34d399;
            font-weight: 600;
        }

        .status-abort {
            color: #f87171;
            font-weight: 600;
        }

        .status-reviewing {
            color: #fbbf24;
            font-weight: 600;
        }

        .status-pass {
            color: #34d399;
            font-weight: 600;
        }

        .status-timing {
            color: #60a5fa;
            font-weight: 600;
        }

        .status-queuing {
            color: #a78bfa;
            font-weight: 600;
        }

        .status-executing {
            color: #f59e0b;
            font-weight: 600;
        }

        .status-wrong {
            color: #f87171;
            font-weight: 600;
        }

        .status-exception {
            color: #ef4444;
            font-weight: 600;
        }

        .loading {
            text-align: center;
            padding: 2rem;
            color: #94a3b8;
        }

        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #64748b;
        }

        .empty-state-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        /* 下拉刷新样式 */
        .pull-refresh-indicator {
            position: fixed;
            top: -40px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            align-items: center;
            gap: 8px;
            color: #94a3b8;
            font-size: 0.85rem;
            font-weight: 500;
            transition: all 0.3s ease;
            z-index: 1000;
            pointer-events: none;
        }

        .pull-refresh-indicator.show {
            top: 20px;
        }

        .pull-refresh-icon {
            font-size: 1.1rem;
            transition: transform 0.3s ease;
            display: inline-block;
        }

        .pull-refresh-indicator.refreshing .pull-refresh-icon {
            animation: pulse 1.5s ease-in-out infinite;
        }

        .pull-refresh-indicator.refresh-ready {
            color: #3b82f6;
        }

        .pull-refresh-indicator.refreshing {
            color: #10b981;
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
                opacity: 1;
            }
            50% {
                transform: scale(1.1);
                opacity: 0.8;
            }
        }

        /* 内容区域支持下拉刷新 */
        #content-detail {
            position: relative;
            transition: transform 0.3s ease;
        }

        #content-detail.pulling {
            transition: none;
        }

        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(8px);
            z-index: 1000;
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modal-overlay.show {
            display: flex;
            opacity: 1;
            align-items: center;
            justify-content: center;
            padding: 20px;
            box-sizing: border-box;
        }

        .modal-content {
            background: rgba(26, 30, 48, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
            width: 100%;
            max-width: 90vw;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            border: 1px solid rgba(148, 163, 184, 0.1);
            transform: scale(0.9);
            transition: transform 0.3s ease;
        }

        .modal-overlay.show .modal-content {
            transform: scale(1);
        }

        .modal-header {
            padding: 20px 24px 16px;
            border-bottom: 1px solid rgba(148, 163, 184, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .modal-title {
            color: #f1f5f9;
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0;
        }

        .modal-close {
            background: none;
            border: none;
            color: #94a3b8;
            font-size: 1.5rem;
            cursor: pointer;
            padding: 4px;
            border-radius: 6px;
            transition: all 0.2s ease;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-close:hover {
            background: rgba(148, 163, 184, 0.1);
            color: #f1f5f9;
        }

        .modal-body {
            padding: 20px 24px;
            flex: 1;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
        }

        .sql-content {
            background: rgba(15, 23, 42, 0.8);
            border: 1px solid rgba(148, 163, 184, 0.1);
            border-radius: 12px;
            padding: 16px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 0.9rem;
            line-height: 1.5;
            color: #e2e8f0;
            white-space: pre-wrap;
            word-break: break-all;
            overflow-x: auto;
            margin-bottom: 16px;
        }

        .modal-footer {
            padding: 16px 24px 20px;
            border-top: 1px solid rgba(148, 163, 184, 0.1);
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .modal-btn {
            border: none;
            color: #fff;
            border-radius: 8px;
            padding: 10px 20px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            min-width: 80px;
        }

        .modal-btn-secondary {
            background: rgba(148, 163, 184, 0.2);
            color: #cbd5e1;
        }

        .modal-btn-secondary:hover {
            background: rgba(148, 163, 184, 0.3);
        }

        .modal-btn-primary {
            background: linear-gradient(135deg, #3b82f6, #60a5fa);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }

        .modal-btn-primary:hover {
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.5);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .content {
                padding: 3%;
            }

            .modal-content {
                max-width: 95vw;
                max-height: 85vh;
                margin: 10px;
            }

            .modal-header {
                padding: 16px 20px 12px;
            }

            .modal-body {
                padding: 16px 20px;
            }

            .modal-footer {
                padding: 12px 20px 16px;
                flex-direction: column;
            }

            .modal-btn {
                width: 100%;
            }

            /* 移动端工单列表优化 */
            .workflow-status {
                flex: 0 0 25%;
                font-size: 0.8rem;
            }

            .workflow-actions {
                flex: 0 0 35%;
                gap: 2px;
            }

            .btn {
                padding: 3px 6px;
                font-size: 0.7rem;
                min-width: 45px;
            }

            .workflow-time {
                font-size: 0.7rem;
            }
        }

        @media (max-width: 480px) {
            .workflow-status {
                flex: 0 0 20%;
                font-size: 0.75rem;
            }

            .workflow-actions {
                flex: 0 0 15%;
                gap: 1px;
            }

            .btn {
                padding: 5px 12px;
                font-size: 0.7rem;
                min-width: 40px;
            }

            .workflow-time {
                font-size: 0.65rem;
            }
        }
    </style>
</head>
<body>
<div class="content">
    <!-- 下拉刷新指示器 - 移到content-detail外部 -->
    <div id="pullRefreshIndicator" class="pull-refresh-indicator">
        <span class="pull-refresh-icon">⏳</span>
        <span id="pullRefreshText">下拉刷新</span>
    </div>

    <div id="content-detail">
        <div class="loading">
            <div>正在加载工单列表...</div>
        </div>
    </div>
</div>

<!-- 参数内容展示模态框 -->
<div id="sqlModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">SQL内容详情</h3>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="sql-content" id="sqlContent"></div>
        </div>
        <div class="modal-footer">
            <button class="modal-btn modal-btn-secondary" onclick="closeModal()">关闭</button>
            <button class="modal-btn modal-btn-primary" onclick="copyToClipboard()">复制</button>
        </div>
    </div>
</div>
<script>
    const params = getQueryParams();

    function getQueryParams() {
        const url = window.location.href;
        const regExp = /[?&]([^=#]+)=([^&#]*)/g;
        let params = {};
        let match;
        while (match = regExp.exec(url)) {
            params[match[1]] = decodeURIComponent(match[2]);
        }
        return params;
    }

    // 状态枚举映射
    const statusMap = {
        'workflow_finish': {text: '正常结束', class: 'status-finish'},
        'workflow_abort': {text: '人工终止', class: 'status-abort'},
        'workflow_manreviewing': {text: '等待审核', class: 'status-reviewing'},
        'workflow_review_pass': {text: '审核通过', class: 'status-pass'},
        'workflow_timingtask': {text: '定时执行', class: 'status-timing'},
        'workflow_queuing': {text: '正在排队', class: 'status-queuing'},
        'workflow_executing': {text: '正在执行', class: 'status-executing'},
        'workflow_autoreviewwrong': {text: '审核拒绝', class: 'status-wrong'},
        'workflow_exception': {text: '执行异常', class: 'status-exception'}
    };

    // 时间格式化函数
    function formatRelativeTime(dateString) {
        if (!dateString) {
            return '';
        }

        const now = new Date();
        const date = new Date(dateString);
        const diffMs = now - date;
        const diffMinutes = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMinutes < 1) {
            return '刚刚';
        } else if (diffMinutes < 60) {
            return diffMinutes + '分钟前';
        } else if (diffHours < 24) {
            return diffHours + '小时前';
        } else if (diffDays < 7) {
            return diffDays + '天前';
        } else {
            // 超过一周显示具体日期
            return date.toLocaleDateString('zh-CN', {
                month: 'short',
                day: 'numeric'
            });
        }
    }

    function initWorkflowTemplate(workflow) {
        const statusInfo = statusMap[workflow.status] || {text: workflow.statusDesc || '未知状态', class: 'status-finish'};
        const actionContent = getActionContent(workflow);

        return '<div class="row" data-id="' + workflow.id + '">' +
            '    <div class="workflow-name">[ '+(workflow.instance__instance_name.split('-')[0])+' ] ' + (workflow.workflow_name || '未命名工单') + '</div>' +
            '    <div class="workflow-status ' + statusInfo.class + '">' + statusInfo.text + '</div>' +
            '    <div class="workflow-actions">' + actionContent + '</div>' +
            '</div>';
    }

    function getActionContent(workflow) {
        const status = workflow.status;
        let content = '';

        // 如果是等待审核状态，显示审核按钮
        if (status === 'workflow_manreviewing') {
            content += `<button class="btn btn-warning" data-action="approve" data-id="${workflow.id}">审核</button>`;
        }
        // 如果是审核通过状态，显示执行按钮
        else if (status === 'workflow_review_pass') {
            content += `<button class="btn btn-danger" data-action="execute" data-id="${workflow.id}">执行</button>`;
        }
        // 其他状态显示创建时间
        else {
            const createTime = formatRelativeTime(workflow.create_time || workflow.created_at);
            if (createTime) {
                content += `<span class="workflow-time">${createTime}</span>`;
            }
        }
        return content;
    }

    // 事件处理函数
    function handleRowClick(event) {
        const row = event.target.closest('.row');
        if (!row) {
            return;
        }

        const id = row.getAttribute('data-id');
        const button = event.target.closest('button');

        // 如果点击的是按钮，执行按钮对应的操作
        if (button) {
            const action = button.getAttribute('data-action');
            if (action === 'approve' && id) {
                approveWorkflow(id);
            } else if (action === 'execute' && id) {
                executeWorkflow(id);
            }
        } else {
            // 如果点击的是行（非按钮），执行查看操作
            if (id) {
                viewResult(id);
            }
        }
    }

    // 审核
    function approveWorkflow(id) {
        fetch(params.host + "/archery/audit", {
            method: 'POST',
            body: JSON.stringify({
                "workflow_id": id
            })
        })
        .then(response => response.text())
        .then(data => {
            loginAndLoadWorkflows();
        });
    }

    // 执行
    function executeWorkflow(id) {
        fetch(params.host + "/archery/execute", {
            method: 'POST',
            body: JSON.stringify({
                "workflow_id": id
            })
        })
        .then(response => response.text())
        .then(data => {
            loginAndLoadWorkflows();
        });
    }

    function viewResult(id) {
        fetch(params.host + "/archery/getById?workflowId=" + id, {
            method: 'GET'
        })
        .then(response => response.text())
        .then(data => {
            let res = JSON.parse(decodeBase64(JSON.parse(data).data));
            let sql_content = "";
            for (let i = 0; i < res.length; i++) {
                sql_content += "[" + res[i].stagestatus + "] " + res[i].sql + ";\n\n";
            }
            // 解码SQL内容（如果是Base64编码）
            let decodedContent;
            try {
                // 尝试解码Base64
                decodedContent = decodeBase64(sql_content);
            } catch (e) {
                // 如果不是Base64，直接使用原内容
                decodedContent = sql_content;
            }

            // 设置SQL内容
            document.getElementById('sqlContent').textContent = decodedContent;

            // 显示模态框
            const modal = document.getElementById('sqlModal');
            modal.classList.add('show');

            // 添加键盘事件监听
            document.addEventListener('keydown', handleKeyDown);

            // 添加点击遮罩层关闭功能
            modal.addEventListener('click', function (e) {
                if (e.target === modal) {
                    closeModal();
                }
            });

        });
    }

    function closeModal() {
        const modal = document.getElementById('sqlModal');
        modal.classList.remove('show');

        // 移除事件监听
        document.removeEventListener('keydown', handleKeyDown);
    }

    function handleKeyDown(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    }

    function copyToClipboard() {
        let sqlContent = document.getElementById('sqlContent').textContent;
        sqlContent = sqlContent.split('\n\n').map(line => line.replace(/^\[.*?\]\s*/, '')).join('\n\n');
        if (navigator.clipboard && window.isSecureContext) {
            // 使用现代 Clipboard API
            navigator.clipboard.writeText(sqlContent).then(function () {
                plus.nativeUI.toast("已复制到剪贴板", {duration: 1500});
            }).catch(function (err) {
                console.error('复制失败:', err);
                fallbackCopy(sqlContent);
            });
        } else {
            // 降级方案
            fallbackCopy(sqlContent);
        }
    }

    function fallbackCopy(text) {
        // 创建临时文本区域
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            const successful = document.execCommand('copy');
            if (successful) {
                plus.nativeUI.toast("已复制到剪贴板", {duration: 1500});
            } else {
                plus.nativeUI.toast("复制失败，请手动复制", {duration: 2000});
            }
        } catch (err) {
            plus.nativeUI.toast("复制失败，请手动复制", {duration: 2000});
        }

        document.body.removeChild(textArea);
    }

    function decodeBase64(base64) {
        return decodeURIComponent(escape(window.atob(base64)))
    }

    // 下拉刷新相关变量
    let pullRefreshState = {
        startY: 0,
        currentY: 0,
        isPulling: false,
        isRefreshing: false,
        threshold: 60, // 触发刷新的阈值
        maxPull: 50   // 最大下拉距离
    };

    // 初始化下拉刷新
    function initPullRefresh() {
        const contentDetail = document.getElementById('content-detail');

        // 先移除之前的事件监听器，避免重复绑定
        contentDetail.removeEventListener('touchstart', handleTouchStart);
        contentDetail.removeEventListener('touchmove', handleTouchMove);
        contentDetail.removeEventListener('touchend', handleTouchEnd);

        // 触摸开始
        contentDetail.addEventListener('touchstart', handleTouchStart, {passive: true});

        // 触摸移动
        contentDetail.addEventListener('touchmove', handleTouchMove, {passive: false});

        // 触摸结束
        contentDetail.addEventListener('touchend', handleTouchEnd, {passive: true});
    }

    // 触摸开始处理函数
    function handleTouchStart(e) {
        if (pullRefreshState.isRefreshing) {
            return;
        }

        pullRefreshState.startY = e.touches[0].clientY;
        pullRefreshState.isPulling = false;
    }

    // 触摸移动处理函数
    function handleTouchMove(e) {
        if (pullRefreshState.isRefreshing) {
            return;
        }

        const contentDetail = document.getElementById('content-detail');
        const indicator = document.getElementById('pullRefreshIndicator');
        const text = document.getElementById('pullRefreshText');

        pullRefreshState.currentY = e.touches[0].clientY;
        const deltaY = pullRefreshState.currentY - pullRefreshState.startY;

        // 只有在顶部且向下拉时才触发
        if (contentDetail.scrollTop === 0 && deltaY > 0) {
            e.preventDefault();

            pullRefreshState.isPulling = true;
            contentDetail.classList.add('pulling');

            // 限制最大下拉距离
            const pullDistance = Math.min(deltaY * 0.15, pullRefreshState.maxPull);
            contentDetail.style.transform = `translateY(${pullDistance}px)`;

            // 显示指示器
            indicator.classList.add('show');

            // 更新指示器状态
            if (pullDistance >= pullRefreshState.threshold) {
                indicator.classList.add('refresh-ready');
                text.textContent = '释放刷新';
            } else {
                indicator.classList.remove('refresh-ready');
                text.textContent = '下拉刷新';
            }
        }
    }

    // 触摸结束处理函数
    function handleTouchEnd(e) {
        if (pullRefreshState.isRefreshing) {
            return;
        }

        const contentDetail = document.getElementById('content-detail');
        const deltaY = pullRefreshState.currentY - pullRefreshState.startY;

        if (pullRefreshState.isPulling) {
            contentDetail.classList.remove('pulling');

            if (deltaY >= pullRefreshState.threshold) {
                // 触发刷新
                triggerRefresh();
            } else {
                // 回弹
                resetPullRefresh();
            }
        }

        pullRefreshState.isPulling = false;
    }

    // 触发刷新
    function triggerRefresh() {
        const indicator = document.getElementById('pullRefreshIndicator');
        const text = document.getElementById('pullRefreshText');

        pullRefreshState.isRefreshing = true;

        // 更新指示器状态
        indicator.classList.remove('refresh-ready');
        indicator.classList.add('refreshing');
        text.textContent = '正在刷新...';

        // 重新加载数据
        loginAndLoadWorkflows();
    }

    // 重置下拉刷新状态
    function resetPullRefresh() {
        const contentDetail = document.getElementById('content-detail');
        const indicator = document.getElementById('pullRefreshIndicator');
        const text = document.getElementById('pullRefreshText');

        // 重置样式
        contentDetail.style.transform = '';
        contentDetail.classList.remove('pulling');

        // 检查元素是否存在（防止innerHTML后元素被删除）
        if (indicator) {
            indicator.classList.remove('show', 'refresh-ready', 'refreshing');
        }
        if (text) {
            text.textContent = '下拉刷新';
        }

        // 重置状态
        pullRefreshState.isRefreshing = false;
        pullRefreshState.isPulling = false;
        pullRefreshState.startY = 0;
        pullRefreshState.currentY = 0;
    }

    function loginAndLoadWorkflows() {
        fetch(params.host + "/archery/list", {
            method: 'POST',
            body: null
        })
        .then(response => {
            return response.text();
        })
        .then(data => {
            try {
                let res = JSON.parse(decodeBase64(JSON.parse(data).data));
                if (!res || res.length === 0) {
                    document.getElementById("content-detail").innerHTML =
                        '<div class="empty-state">' +
                        '    <div class="empty-state-icon">📋</div>' +
                        '    <div>今日暂无工单数据</div>' +
                        '</div>';
                    // 重新初始化下拉刷新
                    initPullRefresh();
                    // 重置下拉刷新状态
                    resetPullRefresh();
                    return;
                }

                let innHtml = '';
                for (var i = 0; i < res.length; i++) {
                    innHtml += initWorkflowTemplate(res[i]);
                }

                document.getElementById("content-detail").innerHTML = innHtml;
                // 重新初始化下拉刷新（因为innerHTML会清除事件监听器）
                initPullRefresh();
                // 重置下拉刷新状态
                resetPullRefresh();
            } catch (error) {
                document.getElementById("content-detail").innerHTML =
                    '<div class="empty-state">' +
                    '    <div class="empty-state-icon">⚠️</div>' +
                    '    <div>数据解析失败</div>' +
                    '</div>';
                // 重新初始化下拉刷新
                initPullRefresh();
                // 重置下拉刷新状态
                resetPullRefresh();
            }
        })
        .catch(error => {
            document.getElementById("content-detail").innerHTML =
                '<div class="empty-state">' +
                '    <div class="empty-state-icon">❌</div>' +
                '    <div>加载失败: ' + error.message + '</div>' +
                '</div>';
            // 重新初始化下拉刷新
            initPullRefresh();
            // 重置下拉刷新状态
            resetPullRefresh();
        });
    }

    // 事件委托处理所有点击事件
    document.getElementById('content-detail').addEventListener('click', function (e) {
        handleRowClick(e);
    });

    document.addEventListener('plusready', function () {
        // 初始化下拉刷新
        initPullRefresh();
        // 加载列表
        loginAndLoadWorkflows();
    });
</script>
</body>
</html>
